import "./ui.less";
import { useKeyboardControls } from "@react-three/drei";
import { useEffect, useRef, useState } from "react";
import { addEffect } from "@react-three/fiber";
import useGame from "../../stores/useGame.js";

function UI() {
  const gameState = useGame((state) => state.gameState);
  const startTime = useGame((state) => state.startTime);
  const endTime = useGame((state) => state.endTime);
  const timeRef = useRef();
  const reStart = useGame((state) => state.reStart);
  const [keys, setKeys] = useState({
    forward: false,
    right: false,
    left: false,
    back: false,
    jump: false,
  });
  const [subKeys, getKeys] = useKeyboardControls();
  useEffect(() => {
    //订阅键盘事件，更新模拟键盘UI
    const unSub = subKeys(
      (state) => state,
      (value) => {
        setKeys(value);
      }
    );

    return () => {
      unSub();
    };
  }, []);
  //订阅动画帧,依赖于gameState
  useEffect(() => {
    //订阅动画帧
    const unSubFream = addEffect(() => {
      let time = 0;
      if (gameState === "playing") {
        time = Date.now() - startTime;
      } else if (gameState === "ended") {
        time = endTime - startTime;
      }
      time = time / 1000;
      time = time.toFixed(2);
      //   console.log('pppp',gameState)
      if (timeRef.current) {
        timeRef.current.innerText = time;
      }
    });

    return () => {
      unSubFream();
    };
  }, [gameState, startTime, endTime]);

  return (
    <>
      <div className="ui">
        <div ref={timeRef} className="time">
          0.00
        </div>
        {gameState === "ended" && (
          <div
            className="restart"
            onClick={() => {
              reStart();
            }}
          >
            重新开始
          </div>
        )}
        <div className="controls">
          <div className="row">
            <div className={keys.forward ? "key active" : "key"}>W</div>
          </div>
          <div className="row">
            <div className={keys.right ? "key active" : "key"}>A</div>
            <div className={keys.back ? "key active" : "key"}>S</div>
            <div className={keys.left ? "key active" : "key"}>D</div>
          </div>
          <div className="row">
            <div className={keys.jump ? "key active large" : "key large"}></div>
          </div>
        </div>
      </div>
    </>
  );
}
export default UI;




